#include "serialportthread.h"

SerialPortThread::SerialPortThread(QString serialNum, int baudRate, QString parity, int dataBit, QString stopBit) : QThread()
, serialNum(serialNum), baudRate(baudRate), parity(parity),
dataBit(dataBit), stopBit(stopBit)
{

}

int SerialPortThread::connectSerial()
{
    try{
        serialConnector = new QSerialPort;
        serialConnector->setPortName(serialNum);
        serialConnector->setBaudRate(baudRate);
        if(parity == "NONE")
            serialConnector->setParity(QSerialPort::NoParity);
        if(parity == "EVEN")
            serialConnector->setParity(QSerialPort::EvenParity);
        if(parity == "ODD")
            serialConnector->setParity(QSerialPort::OddParity);
        if(parity == "MARK")
            serialConnector->setParity(QSerialPort::MarkParity);

        switch (dataBit) {
        case 5:
            serialConnector->setDataBits(QSerialPort::Data5);
            break;
        case 6:
            serialConnector->setDataBits(QSerialPort::Data6);
            break;
        case 7:
            serialConnector->setDataBits(QSerialPort::Data7);
            break;
        case 8:
            serialConnector->setDataBits(QSerialPort::Data8);
            break;
        default:
            return -1;
        }

        if(stopBit == "1")
            serialConnector->setStopBits(QSerialPort::OneStop);
        if(stopBit == "1.5")
            serialConnector->setStopBits(QSerialPort::OneAndHalfStop);
        if(stopBit == "1")
            serialConnector->setStopBits(QSerialPort::TwoStop);

        serialConnector->setFlowControl(QSerialPort::NoFlowControl);
        if (serialConnector->open(QIODevice::ReadWrite)){
            isReady = true;
            return 0;
        } else {
            isReady = false;
            return -1;
        }

    } catch(const std::exception& ex){
        qDebug() << "Error";
        isReady = false;
        return -1;
    }
}

void SerialPortThread::disconnectSerial()
{
    if (isReady){
        serialConnector->close();
        isReady = false;
    }
}

void SerialPortThread::sendSerial(QString cmd)
{
    if(isReady){
        serialConnector->write(cmd.toLatin1());
    }
}

char* SerialPortThread::recv(int size)
{
    char* buf = NULL;
    if (isReady) {
        serialConnector->read(buf, size);
        return buf;
    }
    return buf;
}

SerialPortThread::~SerialPortThread(){
    delete serialConnector;
}
